<template>
  <div>
    <!-- 用户列表 -->
    <ul>
      <li v-for="user in users" :key="user.id">
        {{ user.name }} - {{ user.email }}
      </li>
    </ul>

    <!-- 创建用户表单 -->
    <form @submit.prevent="handleSubmit">
      <input v-model="form.name" placeholder="Name">
      <input v-model="form.email" placeholder="Email">
      <button type="submit">Create</button>
    </form>
  </div>
</template>

<script>
import userApi from '@/api/user'

export default {
  data() {
    return {
      users: [],
      form: {
        name: '',
        email: ''
      }
    }
  },
  async created() {
    // 组件加载时自动获取数据
    await this.loadUsers()
  },
  methods: {
    // 加载用户列表
    async loadUsers() {
      try {
        const response = await userApi.getUsers({ sort: 'name' }) // 示例参数
        this.users = response
      } catch (error) {
        this.$toast.error('加载用户失败: ' + error.message)
      }
    },

    // 提交表单
    async handleSubmit() {
      try {
        await userApi.createUser(this.form)
        this.$toast.success('用户创建成功')
        this.form = { name: '', email: '' } // 清空表单
        await this.loadUsers() // 刷新列表
      } catch (error) {
        this.$toast.error('创建失败: ' + error.message)
      }
    }
  }
}
</script>